<template>
  <div class="system-tenant-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      :close-on-click-modal="false"
      draggable
      width="520px"
    >
      <el-form
        ref="tenantDialogFormRef"
        :model="state.ruleForm"
        :rules="formRules"
        size="default"
      >
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="租户名称" prop="name" label-width="100">
              <el-input
                v-model="state.ruleForm.name"
                placeholder="请输入租户名称"
                clearable
              ></el-input>
              <label class="tenant-msg">留空则切换到主系统</label>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button
            type="primary"
            @click="submitValidate(tenantDialogFormRef)"
            size="default"
            >{{ state.dialog.submitTxt }}</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemTenantDialog">
import { nextTick, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import _ from "lodash";
import { useTenantApi } from "/@/api/tenant/index";

// 定义子组件向父组件传值/事件
const emit = defineEmits(["finish"]);

// 引入租户 Api 请求接口
const tenantApi = useTenantApi();

// 定义变量内容
const tenantDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    name: "", // 租户名称
  },
  dialog: {
    isShowDialog: false,
    title: "切换租户",
    submitTxt: "确定",
  },
});

// 表单验证规则
const formRules = reactive<FormRules>({
  // name: [{ required: true, message: "请输入租户名称！", trigger: "blur" }],
});

// 提交验证
const submitValidate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      onSubmit();
    } else {
      console.warn("未验证通过!", fields);
    }
  });
};

// 打开弹窗
const openDialog = (name: string) => {
  nextTick(() => {
    tenantDialogFormRef.value?.resetFields();
    state.ruleForm.name = name;
    state.dialog.isShowDialog = true;
  });
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = () => {
  if (!state.ruleForm.name) {
    closeDialog(); // 关闭弹窗
    emit("finish", "", "");
    return;
  }
  tenantApi
    .getTenantByName(state.ruleForm.name)
    .then((result) => {
      if (!result.success) {
        ElMessage.warning("该租户不存在！");
        return;
      }
      if (!result.isActive) {
        ElMessage.warning("该租户的管理员账号未激活！");
        return;
      }
      ElMessage.success("切换成功！");
      closeDialog(); // 关闭弹窗
      emit("finish", result.tenantId, result.name);
    })
    .catch((err: any) => {
      console.error("切换出错：", err);
    });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>
.tenant-msg {
  color: #999999;
}
</style>
